package com.access.boot.apisdk.param.resolve.argument;

import com.access.boot.apisdk.RequestContext;
import com.access.boot.apisdk.annotation.Header;
import com.access.boot.apisdk.annotation.ValueConstants;
import com.access.boot.apisdk.param.resolve.AbstractNamedValueMethodArgumentResolver;
import com.access.boot.apisdk.util.MethodParameter;

/**
 * @author YangZhen
 * @date 2022/6/18 15:59
 * @since 1.0.0
 */
public class HeaderMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (!parameter.hasParameterAnnotation(Header.class)) {
            return false;
        }
        return true;
    }

    @Override
    protected void resolveNamedValue(RequestContext httpRequest, String name, MethodParameter parameter, Object[] arguments) {
        Object argument = arguments[parameter.getParameterIndex()];
        if (argument != null) {
            httpRequest.addHeader(name, argument);
        }
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        Header ann = parameter.getParameterAnnotation(Header.class);
        return new RequestHeaderNamedValueInfo(ann);
    }

    private static final class RequestHeaderNamedValueInfo extends NamedValueInfo {

        private RequestHeaderNamedValueInfo(Header annotation) {
            super(annotation.name(), annotation.value(), annotation.required(), ValueConstants.DEFAULT_NONE);
        }
    }

}
